'''jwt知识点'''

'''
1.安装jwt
2.在app目录下新建一个utils工具文件夹
3.新建 JWTencode.py 创建token
        # code
        import jwt
        import datetime
        from django.conf import settings
        
        SALT = settings.SECRET_KEY #密令
        def createToken(payload,timeout):
        
            #1.jwt 用户验证后生成的token
            headers = {
                "alg": "HS256",
                "typ": "JWT"
            }
            # payload = {'user_id': '', 'username': '', 'exp': ''}
            payload['exp'] = datetime.datetime.utcnow() + datetime.timedelta(minutes=timeout)
        
            token = jwt.encode(payload=payload,key=SALT,algorithm="HS256",headers=headers).decode('utf-8')
            return token
        # code
4.新建 JWTdecode.py  解密token,配置全局授权
        #code
        import jwt
        from rest_framework.authentication import BaseAuthentication
        from rest_framework.exceptions import AuthenticationFailed
        from django.conf import settings
        # 获得token,解密token,拿到 payload 的信息
        # payload ={'user_id':'', 'username':'', 'exp':''}
        from rest_framework.response import Response
        
        class JWTQueryParameAustentication(BaseAuthentication):
            def authenticate(self, request):
                SALT = settings.SECRET_KEY
                # 获取token的值
                token = request.query_params.get('token')
                payload = None
                msg = None
        
        
                try:
                    payload = jwt.decode(token, key=SALT, verify=True)
                except jwt.exceptions.ExpiredSignature:
                    msg = f"token失效{token}"
                    raise AuthenticationFailed({'code':1003,'error':msg})
                except jwt.exceptions.DecodeError:
                    msg = f"token认证失败{token}"
                    raise AuthenticationFailed({'code': 1003, 'error': msg})
                except jwt.exceptions.InvalidTokenError:
                    msg = f"非法token{token}"
                    raise AuthenticationFailed({'code': 1003, 'error': msg})
        
        
                print(payload['user_id'],payload['username'])
        
                return (payload,token)
        #code

5. 配置setting文件夹配置完成
在REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': ['app_User.utils.JWTdecode.JWTQueryParameAustentication',],
}

'''